import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @author wangj881
 * @date 2025-01-03 16:09
 */
public class L56_3 {

    public static void main(String[] args) {
//        int[][] nums = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] nums = {{1, 4}, {2, 3}};
        int[][] merge = new Solution().merge(nums);
        for (int[] ints : merge) {
            System.out.println(Arrays.toString(ints));
        }
    }

    static class Solution {
        public int[][] merge(int[][] intervals) {
            ArrayList<int[]> list = new ArrayList<>();

            Arrays.sort(intervals, new Comparator<int[]>() {
                @Override
                public int compare(int[] o1, int[] o2) {
                    return o1[0] - o2[0];
                }
            });


            for (int[] interval : intervals) {
                int size = list.size();
                if (size > 0 && list.get(size - 1)[1] >= interval[0]) {
                    list.get(size - 1)[1] = Math.max(interval[1], list.get(size - 1)[1]);
                } else {
                    list.add(interval);
                }
            }
            int[][] ints = list.toArray(new int[0][]);
            return ints;
        }
    }
}
